/**
 * 任务队列
 */
export class TaskQueue {
  private queue: Function[];
  private isRunning: boolean;

  constructor() {
    this.queue = [];
    this.isRunning = false;
  }

  // 添加函数到队列
  enqueue(fn: () => any) {
    this.queue.push(fn);
    this.run().then(() => void 0);
  }

  // 执行队列中的函数
  async run() {
    if (this.isRunning || this.queue.length === 0) return;
    this.isRunning = true;

    while (this.queue.length > 0) {
      const fn = this.queue.shift();
      if (!fn) continue;
      try {
        const ret = fn();
        if (ret instanceof Promise) {
          await ret;
        }
      } catch (e: any) {
        console.error("Function execution failed:", fn, e);
      }
    }

    this.isRunning = false;
  }
}
